package com.ytangdata.test.rest;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManagerFactory;

import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.event.spi.PostLoadEvent;
import org.hibernate.event.spi.PostLoadEventListener;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.jpa.HibernateEntityManagerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import edu.fudan.mylang.pf.BaseModelObject;
import edu.fudan.mylang.pf.IObjectFactory;

@Component
public class ObjectFactoryInjector implements PostLoadEventListener, BeanFactoryAware{
	
	private static final long serialVersionUID = 6542367678846751305L;
	@Autowired BeanFactory beanFactory;
	@Autowired EntityManagerFactory entityManagerFactory;
	
	@PostConstruct
    private void init() {
        HibernateEntityManagerFactory hibernateEntityManagerFactory = (HibernateEntityManagerFactory) this.entityManagerFactory;
        SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) hibernateEntityManagerFactory.getSessionFactory();
        EventListenerRegistry registry = sessionFactoryImpl.getServiceRegistry().getService(EventListenerRegistry.class);
        registry.appendListeners(EventType.POST_LOAD, this);
    }

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
	}

	@Override
	public void onPostLoad(PostLoadEvent event) {
		if(event.getEntity() instanceof BaseModelObject) {
			((BaseModelObject) event.getEntity()).setObjectFactory((IObjectFactory) beanFactory.getBean("objectFactory"));
			((BaseModelObject)event.getEntity()).entityInitialized(beanFactory);
		}
	}
}
